package org.zwy.gradetrack.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;
import org.zwy.gradetrack.entity.EvaluationMechanism;
import org.zwy.gradetrack.entity.Major;
import org.zwy.gradetrack.service.EvaluationMechanismService;
import org.zwy.gradetrack.service.MajorService;

import java.time.LocalDateTime;

/**
 * 评价机制管理控制器
 */
@RestController
@RequestMapping("/api/evaluation-mechanisms")
public class EvaluationMechanismController {

    @Autowired
    private EvaluationMechanismService evaluationMechanismService;
    
    @Autowired
    private MajorService majorService;

    /**
     * 获取评价机制列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER','GRADUATE')")
    public Result<Page<EvaluationMechanism>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long majorId) {
        
        Page<EvaluationMechanism> page = new Page<>(current, size);
        LambdaQueryWrapper<EvaluationMechanism> wrapper = new LambdaQueryWrapper<>();
        
        if (majorId != null) {
            wrapper.eq(EvaluationMechanism::getMajorId, majorId);
        }
        
        wrapper.orderByDesc(EvaluationMechanism::getCreateTime);
        
        return Result.success(evaluationMechanismService.page(page, wrapper));
    }

    /**
     * 创建评价机制
     */
    @PostMapping
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<EvaluationMechanism> create(@RequestBody EvaluationMechanism mechanism) {
        // 检查专业是否存在
        Major major = majorService.getById(mechanism.getMajorId());
        if (major == null) {
            return Result.error(404, "专业不存在");
        }
        
        // 检查同一专业下是否存在相同名称的机制
        LambdaQueryWrapper<EvaluationMechanism> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EvaluationMechanism::getMajorId, mechanism.getMajorId())
               .eq(EvaluationMechanism::getMechanismName, mechanism.getMechanismName());
        
        if (evaluationMechanismService.count(wrapper) > 0) {
            return Result.error(400, "该专业下已存在相同名称的评价机制");
        }
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        mechanism.setCreateTime(now);
        mechanism.setUpdateTime(now);
        
        evaluationMechanismService.save(mechanism);
        return Result.success(mechanism);
    }

    /**
     * 更新评价机制
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<EvaluationMechanism> update(
            @PathVariable Long id,
            @RequestBody EvaluationMechanism mechanism) {
        
        // 检查机制是否存在
        EvaluationMechanism existingMechanism = evaluationMechanismService.getById(id);
        if (existingMechanism == null) {
            return Result.error(404, "评价机制不存在");
        }
        
        // 检查专业是否存在
        Major major = majorService.getById(mechanism.getMajorId());
        if (major == null) {
            return Result.error(404, "专业不存在");
        }
        
        // 检查同一专业下是否存在相同名称的机制（排除自身）
        LambdaQueryWrapper<EvaluationMechanism> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EvaluationMechanism::getMajorId, mechanism.getMajorId())
               .eq(EvaluationMechanism::getMechanismName, mechanism.getMechanismName())
               .ne(EvaluationMechanism::getId, id);
        
        if (evaluationMechanismService.count(wrapper) > 0) {
            return Result.error(400, "该专业下已存在相同名称的评价机制");
        }
        
        // 设置更新时间
        mechanism.setUpdateTime(LocalDateTime.now());
        mechanism.setId(id);
        
        evaluationMechanismService.updateById(mechanism);
        return Result.success(mechanism);
    }

    /**
     * 删除评价机制
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Void> delete(@PathVariable Long id) {
        // 检查机制是否存在
        if (!evaluationMechanismService.removeById(id)) {
            return Result.error(404, "评价机制不存在");
        }
        return Result.success();
    }

    /**
     * 获取评价机制详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER')")
    public Result<EvaluationMechanism> getById(@PathVariable Long id) {
        EvaluationMechanism mechanism = evaluationMechanismService.getById(id);
        if (mechanism == null) {
            return Result.error(404, "评价机制不存在");
        }
        return Result.success(mechanism);
    }
} 